<template>
  <div class="min-h-screen bg-black video-player-page">
    <!-- 播放器容器 -->
    <div class="relative">
      <div class="aspect-video bg-black">
        <video
          ref="videoPlayer"
          :src="playUrl"
          class="w-full h-full"
          controls
          autoplay
          @ended="onVideoEnded"
          @timeupdate="onTimeUpdate"
        >
          您的浏览器不支持视频播放
        </video>
      </div>
    </div>

    <!-- 视频信息和剧集选择 -->
    <div class="container mx-auto px-4 py-6">
      <div class="grid grid-cols-1 lg:grid-cols-3 gap-6">
        <!-- 左侧视频信息 -->
        <div class="lg:col-span-2">
          <el-card class="video-card">
            <h1 class="text-2xl font-bold text-white mb-2">
              {{ movie?.title }}
              <span v-if="currentVideo?.episodeNumber" class="text-lg text-gray-400 ml-2">
                第{{ currentVideo.episodeNumber }}集
              </span>
            </h1>

            <div class="flex items-center gap-4 text-gray-400 text-sm mb-4">
              <span>{{ movie?.year }}</span>
              <span>{{ movie?.country }}</span>
              <span>{{ movie?.genre }}</span>
              <span class="flex items-center">
                <el-icon class="mr-1"><View /></el-icon>
                {{ movie?.viewCount || 0 }}次播放
              </span>
            </div>

            <p class="text-gray-400 line-clamp-3 mb-6">
              {{ movie?.introduction }}
            </p>

            <!-- 操作按钮 -->
            <div class="flex flex-wrap gap-4">
              <el-button @click="toggleCollection">
                <el-icon class="mr-2" :color="isCollected ? '#F7BA2A' : ''">
                  <component :is="isCollected ? StarFilled : Star" />
                </el-icon>
                {{ isCollected ? '已收藏' : '收藏' }}
              </el-button>

              <el-button @click="shareVideo" :icon="Share">
                分享
              </el-button>

              <el-button @click="downloadVideo" :icon="Download">
                下载
              </el-button>
            </div>
          </el-card>
        </div>

        <!-- 右侧剧集列表 -->
        <el-card class="video-card">
          <template #header>
            <h2 class="text-lg font-semibold">剧集列表</h2>
          </template>

          <div class="max-h-[600px] overflow-y-auto">
            <div class="grid grid-cols-4 lg:grid-cols-3 gap-2">
              <el-button
                v-for="video in videoResources"
                :key="video.resourceId"
                :type="video.resourceId === currentResourceId ? 'primary' : 'default'"
                size="small"
                @click="switchEpisode(video)"
                class="text-xs"
              >
                {{ video.episodeNumber }}
              </el-button>
            </div>
          </div>
        </el-card>
      </div>

      <!-- 评论区 -->
      <el-card class="mt-6 video-card">
        <template #header>
          <h2 class="text-lg font-semibold">评论</h2>
        </template>

        <!-- 发表评论 -->
        <div v-if="isLoggedIn" class="mb-6">
          <el-input
            v-model="commentContent"
            type="textarea"
            placeholder="写下你的评论..."
            :rows="3"
            class="mb-3"
          />
          <div class="flex justify-end">
            <el-button type="primary" @click="submitComment">发表评论</el-button>
          </div>
        </div>
        <div v-else class="mb-6 text-center py-4 bg-gray-900 rounded">
          <p class="text-gray-400 mb-2">登录后才能发表评论</p>
          <el-button size="small" @click="navigateTo('/login')">立即登录</el-button>
        </div>

        <!-- 评论列表 -->
        <div class="space-y-4">
          <div v-for="comment in comments" :key="comment.commentId" class="border-b border-gray-700 pb-4">
            <div class="flex items-start gap-3">
              <el-avatar :src="comment.userAvatar" :alt="comment.userName" :size="40" />
              <div class="flex-1">
                <div class="flex items-center gap-2 mb-1">
                  <span class="font-medium text-white">{{ comment.userName }}</span>
                  <span class="text-xs text-gray-500">{{ formatDate(comment.createTime) }}</span>
                </div>
                <p class="text-gray-400">{{ comment.content }}</p>
              </div>
            </div>
          </div>
        </div>
      </el-card>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ElMessage } from 'element-plus'
import { StarFilled, Star, Share, Download, View } from '@element-plus/icons-vue'

const route = useRoute()
const router = useRouter()
const userStore = useUserStore()

// 获取参数
const currentResourceId = computed(() => Number(route.params.id))
const columnValue = computed(() => route.params.columnValue as string)

// refs
const videoPlayer = ref<HTMLVideoElement>()

// 状态
const isCollected = ref(false)
const commentContent = ref('')
const playUrl = ref('')
const movie = ref<any>(null)
const currentVideo = ref<any>(null)
const videoResources = ref<any[]>([])
const comments = ref<any[]>([])

// 获取当前视频信息
const getCurrentVideo = async () => {
  try {
    const data = await $fetch(`/dev-api/movie/resource/${currentResourceId.value}`, {
      headers: token.value ? {
        'Authorization': `Bearer ${userStore.token}`
      } : {}
    })

    if (data.code === 200) {
      currentVideo.value = data.data
      playUrl.value = data.data.playUrl

      // 获取影片信息
      await getMovieDetail()
      await getVideoResources()
    }
  } catch (error) {
    console.error('获取视频信息失败:', error)
  }
}

// 获取影片信息
const getMovieDetail = async () => {
  if (!currentVideo.value?.movieBasicsId) return

  try {
    const data = await $fetch(`/dev-api/movie/basics/${currentVideo.value.movieBasicsId}`, {
      headers: token.value ? {
        'Authorization': `Bearer ${userStore.token}`
      } : {}
    })

    if (data.code === 200) {
      movie.value = data.data
    }
  } catch (error) {
    console.error('获取影片详情失败:', error)
  }
}

// 获取所有剧集
const getVideoResources = async () => {
  if (!currentVideo.value?.movieBasicsId) return

  try {
    const data = await $fetch('/dev-api/movie/resource/list', {
      headers: token.value ? {
        'Authorization': `Bearer ${userStore.token}`
      } : {},
      params: {
        movieBasicsId: currentVideo.value.movieBasicsId
      }
    })

    if (data.code === 200) {
      videoResources.value = data.rows || []
    }
  } catch (error) {
    console.error('获取视频资源失败:', error)
  }
}

// 获取评论
const getCommentList = async () => {
  if (!currentVideo.value?.movieBasicsId) return

  try {
    const data = await $fetch('/dev-api/movie/comment/list', {
      headers: token.value ? {
        'Authorization': `Bearer ${userStore.token}`
      } : {},
      params: {
        movieBasicsId: currentVideo.value.movieBasicsId,
        pageNum: 1,
        pageSize: 10
      }
    })

    if (data.code === 200) {
      comments.value = data.rows || []
    }
  } catch (error) {
    console.error('获取评论列表失败:', error)
  }
}

// 检查收藏状态
const checkCollectionStatus = async () => {
  if (!userStore.isLoggedIn || !currentVideo.value?.movieBasicsId) return

  try {
    const data = await $fetch('/dev-api/member/collection/check', {
      headers: {
        'Authorization': `Bearer ${userStore.token}`
      },
      params: {
        movieBasicsId: currentVideo.value.movieBasicsId
      }
    })

    if (data.code === 200) {
      isCollected.value = data.data || false
    }
  } catch (error) {
    console.error('检查收藏状态失败:', error)
  }
}

// 切换剧集
const switchEpisode = (video: any) => {
  router.push(`/column/${columnValue.value}/video/${video.resourceId}`)
}

// 视频播放结束
const onVideoEnded = () => {
  // 自动播放下一集
  const currentIndex = videoResources.value.findIndex(v => v.resourceId === currentResourceId.value)
  if (currentIndex >= 0 && currentIndex < videoResources.value.length - 1) {
    const nextVideo = videoResources.value[currentIndex + 1]
    switchEpisode(nextVideo)
  }
}

// 时间更新
const onTimeUpdate = () => {
  recordWatchHistory()
}

// 切换收藏
const toggleCollection = async () => {
  if (!userStore.isLoggedIn) {
    router.push('/login')
    return
  }

  if (!currentVideo.value?.movieBasicsId) return

  try {
    if (isCollected.value) {
      const data = await $fetch('/dev-api/member/collection/remove', {
        method: 'DELETE',
        headers: {
          'Authorization': `Bearer ${userStore.token}`
        },
        params: {
          movieBasicsId: currentVideo.value.movieBasicsId
        }
      })

      if (data.code === 200) {
        isCollected.value = false
        ElMessage.success('已取消收藏')
      }
    } else {
      const data = await $fetch('/dev-api/member/collection/add', {
        method: 'POST',
        headers: {
          'Authorization': `Bearer ${userStore.token}`
        },
        body: {
          movieBasicsId: currentVideo.value.movieBasicsId
        }
      })

      if (data.code === 200) {
        isCollected.value = true
        ElMessage.success('收藏成功')
      }
    }
  } catch (error: any) {
    ElMessage.error(error.data?.msg || '操作失败')
  }
}

// 分享
const shareVideo = () => {
  const title = `${movie.value?.title} 第${currentVideo.value?.episodeNumber}集`

  if (navigator.share) {
    navigator.share({
      title,
      url: window.location.href
    }).catch(() => {})
  } else {
    navigator.clipboard.writeText(window.location.href)
    ElMessage.success('链接已复制到剪贴板')
  }
}

// 下载
const downloadVideo = () => {
  if (playUrl.value) {
    window.open(playUrl.value, '_blank')
  } else {
    ElMessage.warning('暂无下载链接')
  }
}

// 提交评论
const submitComment = async () => {
  if (!commentContent.value.trim()) {
    ElMessage.warning('请输入评论内容')
    return
  }

  if (!currentVideo.value?.movieBasicsId) return

  try {
    const data = await $fetch('/dev-api/movie/comment/add', {
      method: 'POST',
      headers: {
        'Authorization': `Bearer ${userStore.token}`
      },
      body: {
        movieBasicsId: currentVideo.value.movieBasicsId,
        content: commentContent.value
      }
    })

    if (data.code === 200) {
      ElMessage.success('评论发表成功')
      commentContent.value = ''
      await getCommentList()
    } else {
      ElMessage.error(data.msg || '评论发表失败')
    }
  } catch (error: any) {
    ElMessage.error(error.data?.msg || '评论发表失败')
  }
}

// 记录观看历史和进度
let historyTimer: any = null
const recordWatchHistory = () => {
  if (!userStore.isLoggedIn || !videoPlayer.value || !currentVideo.value) return

  // 节流：每30秒记录一次
  if (historyTimer) return

  historyTimer = setTimeout(async () => {
    const currentTime = videoPlayer.value?.currentTime || 0
    const duration = videoPlayer.value?.duration || 0

    if (duration > 0) {
      try {
        await $fetch('/dev-api/member/history/record', {
          method: 'POST',
          headers: {
            'Authorization': `Bearer ${userStore.token}`
          },
          body: {
            movieBasicsId: currentVideo.value.movieBasicsId,
            resourceId: currentVideo.value.resourceId,
            episodeNumber: currentVideo.value.episodeNumber,
            watchDuration: Math.floor(currentTime),
            totalDuration: Math.floor(duration),
            watchProgress: Math.floor((currentTime / duration) * 100)
          }
        })
      } catch (error) {
        // 静默失败
      }
    }

    historyTimer = null
  }, 30000)
}

// 增加播放次数
const increaseViewCount = async () => {
  if (!currentVideo.value?.movieBasicsId) return

  try {
    await $fetch('/dev-api/movie/basics/view', {
      method: 'POST',
      params: {
        movieBasicsId: currentVideo.value.movieBasicsId
      }
    })
  } catch (error) {
    // 静默失败
  }
}

// 格式化日期
const formatDate = (dateStr: string) => {
  if (!dateStr) return '-'
  const date = new Date(dateStr)
  return date.toLocaleDateString('zh-CN')
}

// 初始化
onMounted(async () => {
  await getCurrentVideo()
  await getCommentList()
  await checkCollectionStatus()
  increaseViewCount()
})

onUnmounted(() => {
  if (historyTimer) {
    clearTimeout(historyTimer)
  }
  // 离开页面时最后记录一次
  recordWatchHistory()
})

// SEO设置
useSeoMeta({
  title: `${movie.value?.title} 第${currentVideo.value?.episodeNumber}集`,
  description: movie.value?.introduction,
})
</script>

<style scoped lang="scss">
.video-player-page {
  background-color: #0f0f0f;
}

.video-card {
  background-color: rgba(17, 24, 39, 0.9);
  border: 1px solid rgba(55, 65, 81, 0.5);
}

:deep(.el-card__header) {
  background-color: transparent;
  border-bottom: 1px solid rgba(55, 65, 81, 0.5);
  padding: 16px 20px;
  color: white;
}

:deep(.el-card__body) {
  padding: 20px;
}

:deep(.el-input__wrapper),
:deep(.el-textarea__inner) {
  background-color: rgba(17, 24, 39, 0.5);
  color: white;
}

:deep(.el-button--default) {
  background-color: transparent;
  border-color: rgba(55, 65, 81, 0.5);
  color: rgba(255, 255, 255, 0.8);
}

:deep(.el-button--default:hover) {
  background-color: rgba(55, 65, 81, 0.3);
  border-color: #409EFF;
  color: #409EFF;
}
</style>